<template>
  <!-- 添加或修改项目基础信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <div class="app-container" style="display: flex;">
      <div style="width: 25%">
        <el-card class="box-card">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="请购单号" prop="nos">
              <el-input v-model="form.nos" placeholder="保存后自动生成" disabled/>
            </el-form-item>
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请选择客户名称"/>
            </el-form-item>
            <el-form-item label="请购人" prop="userId">
              <el-select v-model="form.userId" placeholder="请选择请购人" filterable @change="selectUser" clearable>
                <el-option v-for="dict in dict.type.sys_user" ref="myselectUser"
                           :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="业务类型" prop="ywType">
              <el-select v-model="form.ywType" placeholder="请选择业务类型" clearable>
                <el-option v-for="dict in dict.type.yewu_type"
                           :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="采购类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择采购类型" clearable>
                <el-option v-for="dict in dict.type.caigou_type"
                           :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="请购日期" prop="ddDate">
              <el-date-picker clearable
                              v-model="form.ddDate"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择请购日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="需求日期" prop="subDate">
              <el-date-picker clearable
                              v-model="form.subDate"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择需求日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请选择备注"/>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
      <div style="width:75%;margin-left: 10px;">
        <el-card class="box-card">
          <el-form :inline="true" :model="queryParams" label-width="98px" ref="queryForm" size="small"
                   v-show="showSearch">
            <el-form-item label="产品编号" prop="code">
              <el-input v-model="queryParams.code" placeholder="请输入产品编号" style="width: 150px;"
                        clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="产品名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入产品名称" style="width: 150px;"
                        clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="产品型号" prop="model">
              <el-input v-model="queryParams.model" placeholder="请输入产品型号" style="width: 150px;"
                        clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item>
              <div style=" display: flex;align-items: center;">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                <el-button type="primary" size="mini" @click="submitFormBuy">添 加</el-button>
              </div>
            </el-form-item>
          </el-form>
          <el-form ref="form1" :model="form1" :rules="rules">
            <el-table border v-loading="loading" :data="columns" @selection-change="handleSelectionChange" @row-click="handleRowClick" ref="multipleTable"
                      :max-height="500">
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="产品编码" align="center" prop="code"/>
              <el-table-column label="产品名称" align="center" prop="name"/>
              <el-table-column align="center" label="产品类别" prop="goodsType">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.goods_type" :value="scope.row.type"/>
                </template>
              </el-table-column>
              <el-table-column label="产品型号" align="center" prop="model"/>
              <el-table-column label="产品单位" align="center" prop="unit"/>
              <el-table-column label="库存数量" align="center" prop="count"/>
              <el-table-column label="可用数量" align="center" prop="remainderCount"/>
              <el-table-column label="请购数量" align="center" prop="counts" width="210">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.counts" @keyup.enter.native="blurOnEnter" @click.native="$event.stopPropagation()" :min="null"
                         size="mini"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="备注" width="210">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remark" @click.native="$event.stopPropagation()"/>
                </template>
              </el-table-column>
              <el-table-column label="发生日期" width="200">
                <template slot-scope="scope">
                  <el-date-picker clearable style="width: 160px" size="mini"
                                  v-model="scope.row.buyDate"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="请选择发生日期">
                  </el-date-picker>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
          <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getList"/>
        </el-card>
      </div>
    </div>
    <el-card class="box-card">
      <el-table :data="columns2" ref="dragTable" row-key="id" v-loading="loading2">
        <el-table-column align="center" label="序号" type="index" width="50">
          <template slot-scope="scope">
            <span>{{ (queryParams2.pageNum - 1) * queryParams2.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品编码" align="center" prop="goodsCode"/>
        <el-table-column align="center" label="产品名称" prop="goodsName"/>
        <el-table-column align="center" label="产品型号" prop="goodModel"/>
        <el-table-column align="center" label="产品单位" prop="unit"/>
        <el-table-column align="center" label="请购申请数量" prop="pleaseBuyApplyCount"/>
       <el-table-column label="备注" width="210">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remark"/>
                </template>
              </el-table-column>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template slot-scope="scope">
            <el-popconfirm :title="`确认删除 `+scope.row.goodsName+` 数据项？`" @confirm="handleDelete(scope.row)"
                           style="margin-left: 10px;">
              <el-button icon="el-icon-delete" size="mini" slot="reference" type="text">删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitScalado" v-if="">提交请购</el-button>
      <!--      <el-button type="primary" @click="submitForm">发起采购</el-button>-->
      <el-button @click="cancel">取 消</el-button>
    </div>
    <upload-dialog ref="uploadDialog" @ok="getList" @handleFileSuccess="handleFileSuccess"></upload-dialog>

  </el-dialog>
</template>

<script>
import UploadDialog from "@/views/upload/UploadDialog.vue";
import {addAction, deleteAction, getAction, getById, updateAction} from '@/api/manage'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {treeselect} from "@/api/system/dept";

export default {
  name: "AddqinggouIronForm",
  dicts: ['goods_customer', 'goods_type', 'yewu_type', 'caigou_type', 'sys_user'],
  components: {
    UploadDialog,
    Treeselect,
  },
  data() {
    return {
      proId: '',
      ironRecordId: '',
      // 遮罩层
      title: "铁件请购",
      loading: false,
      open: false,
      // 选中数组
      ids: [],
      proStatus: "",
      saleType: "2",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库信息管理表格数据
      dataList: [],
      columns: [],
      baseInfoOptions: [],
      deptOptions: [],
      userInfoOptions: [],
      form: {
        nos: null,
        code: null,
        mainId: null,
        deptName: null,
        userName: this.$store.getters.nickName,
        userId: this.$store.getters.userId,
        customerId: null,
        customerName: null,
        ywType: null,
        type: '7',
        ddDate: null,
        subDate: null,
        remark: null,
      },
      form1: {},
      rules: {
        customerName: [
          {required: true, message: "客户名称不能为空", trigger: "blur"},
        ],
        userId: [
          {required: true, message: "i不能为空", trigger: "blur"},
        ],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        model: null,
        brand: null,
        unit: null,
        costPrice: null,
        count: null,
        cost: null,
        validityTerm: null,
        buyId: null,
        buyName: null,
        buyDate: null,
        buyType: null,
        reimburse: null,
        supplierId: null,
        supplierName: null,
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 1000,
        id: null,
        name: null,
        model: null,
        brand: null,
        taxNo: null,
        addr: null,
        tel: null,
        bankName: null,
        bankNo: null,
        info: null,
        delFlag: null,
        createBy: this.$store.getters.name,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        status: "2",
        type: "其他",
        orderByColumn: 'createTime',
        isAsc: 'asc',
      },
      total2: '',
      loading2: '',
      columns2: [],
      url: {
        list: '/goodsOrderIn/goodsOrderIn/list',
        remove: '/goodsSaledo/goodsSaledo/',
        export: '/goodsOrderIn/goodsOrderIn/export',
        insertPleaseBuyForIron: '/goodsSale/goodsSale/insertPleaseBuyForIron',
        list2: '/goodsSale/goodsSale/listSaleProject',
        remove2: '/goodsSaledo/goodsSaledo/deleteProject/',
        submitScalado: '/goodsSaledo/goodsSaledo/submitScalado',
        submitIron: '/goodsSaledo/goodsSaledo/insertBatchIron',
        submitLvdoToCg: '/goodsSaledo/goodsSaledo/submitLvdoToCg',
        //listDo: '/goodsSaledo/goodsSaledo/listSaleProject',
        listDo: '/goodsSaledo/goodsSaledo/list',
        baseInfoList: '/projectBaseInfo/projectBaseInfo/list',
        userInfoList: '/system/user/list',
      },
      tableMaxHeight: window.innerHeight - 900,
    };
  },
  created() {
    this.getTreeselect();
    this.getBaseInfoOptions();
    //this.getUser();
  },
  mounted() {
    document.addEventListener('keydown', this.handleEnterKey);
  },
  beforeDestroy() {
    document.removeEventListener('keydown', this.handleEnterKey);
  },
  methods: {
    submitForm() {
      let that = this;
      if (that.columns2.length > 0) {
        const param = Object.assign({});
        param.nos = that.form.nos;
        param.mainId = that.form.mainId;
        param.deptId = that.form.deptId;
        param.deptName = that.form.deptName;
        param.userId = that.form.userId;
        param.userName = that.form.userName;
        param.customerId = that.form.customerId;
        param.customerName = that.form.customerName;
        param.ywType = that.form.ywType;
        param.type = that.form.type;
        param.ddDate = that.form.ddDate;
        param.subDate = that.form.subDate;
        param.remark = that.form.remark;
        param.columns = that.columns2;
        addAction(this.url.submitLvdoToCg, param).then(response => {
          //this.refreshPageData();
          that.$emit('ok');
          that.$modal.msgSuccess("提交请购成功!");
          that.open = false;
          that.handleQuery();
        }).catch(() => {
        });
      } else {
        alert("没有可请购产品，请选择产品后再次提交！");
      }
    },
    getUser() {
      let params = {
        pageNum: 1,
        pageSize: 1000,
      };
      getAction(this.url.userInfoList, params).then(response => {
        this.userInfoOptions = response.rows;
      });
    },
    getBaseInfoOptions() {
      let params = {
        pageNum: 1,
        pageSize: 1000,
      };
      getAction(this.url.baseInfoList, params).then(response => {
        this.baseInfoOptions = response.rows;
      });
    },
    selectDept(e) {
      let that = this;
      that.$set(that.form, "deptName", e.label);
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    selectUser(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectUser;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.userName = arr[i].label;
          }
        }
      })
    },
    selectCustomer(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectCustomer;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.customerName = arr[i].label;
          }
        }
      })
    },
    handleFileSuccess(response, file, fileList) {
      this.$refs.uploadDialog.open = false;
      this.$refs.uploadDialog.isUploading = false;
      if (response.data.code == "200") {
        this.$alert("导入数据：" + response.data.num + "条！更新数据：" + response.data.numupdate + "条！" + response.data.errorText, "导入结果", {dangerouslyUseHTMLString: true});
      } else {
        this.$alert("导入数据：" + response.data.num + "条！更新数据：" + response.data.numupdate + "条！" + response.data.errorText, "导入结果", {dangerouslyUseHTMLString: true});
      }
      this.getList();
    },
    showUploadDialog() {
      this.$refs.uploadDialog.title = "信息导入";
      this.$refs.uploadDialog.tmplName = "订单信息模板.xlsx";
      this.$refs.uploadDialog.fileName = "订单信息.xlsx";
      this.$refs.uploadDialog.uploadUrl = "/projectBaseInfo/projectBaseInfo/importData";
      this.$refs.uploadDialog.show();
    },
    getList2() {
      this.loading2 = true;
      getAction(this.url.listDo, this.queryParams2).then(response => {
        this.columns2 = response.rows;
        for (let i = 0; i < this.columns2.length; i++) {
          this.columns2[i].idx= i+1;
        }
        this.total2 = response.total;
        this.loading2 = false;
      });
    },
    handleAdd() {
      this.open = true;
      this.loading = false;
      this.reset();
      this.getList2();
      this.form.source = "2";
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        nos: null,
        code: null,
        mainId: null,
        deptId: null,
        deptName: null,
        userName: this.$store.getters.nickName,
        userId: this.$store.getters.userId,
        customerId: null,
        customerName: null,
        ywType: "1",
        type: "7",
        ddDate: new Date(),
        subDate: null,
        remark: null,
      };
      this.resetForm("form");
    },
    refreshPageData() {
      let that = this;
      let param = {
        id: that.proId
      }
      that.handleUpdate(param);
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove, ids).then(response => {
        //this.refreshPageData();
        this.queryParams2.pageNum = 1;
        this.getList2();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleChangeMoney(row) {
      let that = this;
      let handleReckonMoney = (row) => {
        let row_money = 0;
        row_money = that.functionNumberMul(Number(row.goodsUnitPrice), Number(row.goodsCount))
        that.$set(row, 'goodsTotalPrice', row_money);
      };
      handleReckonMoney(row);
    },
    functionNumberMul(arg1, arg2) {
      var m = 0;
      var s1 = arg1.toString();
      var s2 = arg2.toString();
      try {
        m += s1.split(".")[1].length;
      } catch (e) {
      }
      try {
        m += s2.split(".")[1].length;
      } catch (e) {
      }
      return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    },
    chose(proId, type) {
      this.open = true;
      this.proId = proId;
      this.saleType = type;
      this.getList2();
    },
    choseByIronRecord(ironRecordId, proId, type) {
      this.open = true;
      this.proId = proId;
      this.ironRecordId = ironRecordId;
      this.queryParams2.type = type;
      this.saleType = type;
      this.getList2();
    },
    getList() {
      this.loading = true;
      getAction(this.url.list, this.queryParams).then(response => {
        let res = response.rows;
        for (let i = 0; i < res.length; i++) {
          res[i].buyDate = new Date();
        }
        this.columns = res;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.resetForm("queryForm"); // 清空搜索条件

    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.reset();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.dataList = selection;
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    submitScalado() {
      let that = this;
      if (that.columns2.length > 0) {
        const prams = Object.assign({});
        prams.nos = that.form.nos;
        prams.mainId = that.form.mainId;
        prams.deptId = that.form.deptId;
        prams.deptName = that.form.deptName;
        prams.userId = that.form.userId;
        prams.userName = that.form.userName;
        prams.customerId = that.form.customerId;
        prams.customerName = that.form.customerName;
        prams.ywType = that.form.ywType;
        prams.type = that.form.type;
        prams.ddDate = that.form.ddDate;
        prams.subDate = that.form.subDate;
        prams.remark = that.form.remark;
        prams.goodsSaledoList = that.columns2;
        addAction(this.url.submitIron, prams).then(response => {
          //this.refreshPageData();
          that.$emit('ok');
          that.$modal.msgSuccess("提交请购成功!");
          that.open = false;
          that.handleQuery();
        }).catch(() => {
        });
      } else {
        that.$modal.msgError("没有可请购产品，请选择产品后再次提交！!");
      }
    },
    /** 提交按钮 */
    submitFormBuy() {
      let that = this;
      const ids = this.ids;

      if (ids == null || ids == '' || ids == 'undefined') {
        that.$modal.msgError("请选择一条记录");
      } else {
        that.$refs["form1"].validate(valid => {
          if (valid) {
            const param = Object.assign({});
            param.columnsDo = that.dataList;
            addAction(that.url.insertPleaseBuyForIron, param).then(response => {
              that.$modal.msgSuccess("添加成功");
              // this.open = false;
              that.$emit('ok');
              // this.queryParams2.pageNum = 1
              // this.queryParams2.pageSize = 1000
              that.getList2();
              that.handleQuery();
            });
          }
        });
      }
    },
    handleEnterKey(event) {
      if (event.keyCode === 13) {
        this.$refs.elInputNumber.$refs.input.blur()
        this.submitFormBuy();
        this.$forceUpdate();
      }
    },
    blurOnEnter(event) {
      if (event.key === 'Enter') {
        event.target.blur();
        this.submitFormBuy();
      }
    },
  }
};
</script>
